//
//  ViewController.swift
//  NetWorking_Demo
//
//  Created by Jack Wang on 2018/11/15.
//  Copyright © 2018 Jack Wang. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        getModel()
    }
    
    // 网络请求Get
    func smsTestMessage(){
        // 1.初始化一个URL
        let url = URL.init(string: "http://sms.skyerkj.com/Api.php")
        
        // 初始化一个请求对象 携带请求的内容
        var request = URLRequest.init(url: url!)
        request.httpMethod = "GET"
        
        // 创建一个请求任务
        let shareSession = URLSession.shared
        
        let task = shareSession.dataTask(with: request) { (data, res, err) in
           
            if err == nil{
                do{
                    let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
                    
                    print("-----------",dic)
                }catch{
                    print("----------------error:\(String(describing: err))")
                }
            }
        }
        task.resume()
    }

    // 网络请求POST
    func smsPOSTMessage(){
        // 1.初始化一个URL
        let url = URL.init(string: "http://sms.skyerkj.com/api_post.php")
        
        // 初始化一个请求对象 携带请求的内容
        var request = URLRequest.init(url: url!)
        request.httpMethod = "POST"
        let dic : Dictionary = ["test":"1900","test2": "88888","test3":"999999"]
        
        
//        request.httpBody = parmasStringWithParmas(dic as NSDictionary)
        
        // 创建一个请求任务
        let shareSession = URLSession.shared
        
        let task = shareSession.dataTask(with: request) { (data, res, err) in
            
            if err == nil{
                do{
                    let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
                    
                    print("-----------",dic)
                }catch{
                    print("----------------error:\(String(describing: err))")
                }
            }
        }
        task.resume()
    }
    
    
    func parmasStringWithParmas(_ parmas:NSDictionary)->NSString{
        
        let parString = NSMutableString();
        let arr = parmas.allKeys as NSArray;
        for i in 0 ..< arr.count{
            let key = arr[i] as! String;
            let value = parmas.object(forKey: arr[i]) as! NSString;
            parString.appendFormat("%@=%@", key,value);
            
            let lastKey = arr.lastObject as! String;
            if (key != lastKey) {
                
                parString.appendFormat("&");
            }
        }
        return parString;
    }
    
    
    
    
    // POST 请求
    func postModel(){
        
        // 这个session可以使用刚才创建的。
        let session = URLSession(configuration: .default)
        // 设置URL
        let url = "http://sms.skyerkj.com/api_post.php"
        var request = URLRequest(url: URL(string: url)!)
//        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        // 设置要post的内容，字典格式
        let postData = ["email":"user@xxx.com","password":"123456"]
        let postString = postData.compactMap({ (key, value) -> String in
            return "\(key)=\(value)"
        }).joined(separator: "&")
        request.httpBody = postString.data(using: .utf8)
        // 后面不解释了，和GET的注释一样
        let task = session.dataTask(with: request) {(data, response, error) in
            do {
                let r = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
                print(r)
            } catch {
                print("无法连接到服务器")
                return
            }
        }
        task.resume()
    }
    
    
    
    func getModel(){
        // 创建一个会话，这个会话可以复用
        let session = URLSession(configuration: .default)
        // 设置URL
        let url = "http://sms.skyerkj.com/api_get.php"
        let UrlRequest = URLRequest(url: URL(string: url)!)
        // 创建一个网络任务
        let task = session.dataTask(with: UrlRequest) {(data, response, error) in
            do {
                // 返回的是一个json，将返回的json转成字典r
                let r = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary
                print(r)
            } catch {
                // 如果连接失败就...
                print("无法连接到服务器")
                return
            }
        }
        // 运行此任务
        task.resume()
    }
    
    
}

